<template>
  <el-input
      v-model="filterText"
      style="width: 240px"
      placeholder="Filter keyword"
  />
  <el-tree
      ref="treeRef"
      style="max-width: 600px"
      :data="data"
      :props="defaultProps"
      @node-click="handleNodeClick"
      default-expand-all
      :filter-node-method="filterNode"
  >
    <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ data.name }}</span>
          <span>
            <el-link  @click="append(node,data)" type="primary">添加</el-link>
            <el-link style="margin-left: 8px" @click="remove(node, data)" type="danger">删除</el-link>
          </span>
        </span>
    </template>
  </el-tree>
</template>

<script setup>
  const defaultProps = {
    children:'children',
    label:'name'
  }
  //用来接收树形控件的变量
  const treeRef = ref()
  const filterText = ref('')
  //监视filterText属性值，一旦属性改变 回调匿名函数并传入改变后的值
  watch(filterText, (val) => {
    treeRef.value.filter(val)
  })
  //el-tree绑定的 用来过滤节点，决定是否展示的方法
  const filterNode = (value, data) => {
    if (!value) return true //返回true表示展示节点
    return data.name.toUpperCase().includes(value.toUpperCase())
  }
  const data = ref([
    {
      id:1,
      name:'湖北',
      children:[
        {
          name:'武汉市',
            children:[
              {
                name:'江夏区'
              }
            ]
        }
      ]
    },
    {
      id:2,
      name:'湖南'
    },
    {
      id:3,
      name:'河北'
    }
  ])

  const append = (node,data)=>{
    console.log(`给上级节点${data.name}新增下级节点数据`)
  }

  const remove = (node,data)=>{
    console.log(`删除节点${data.name}`)
  }

</script>

<style scoped>

</style>